#include "media_list.h"
char *next_name(char *path)
{
	char *p;
	p=strrchr(path,'/');

	return p+1;
}
ch_list * mlib_getchnlist()
{
	struct stat buf;
	int chnum;
    char *sp;
    ch_list *list;
	glob_t pglob;
	int i=0,fp,pos=0,size=0,len=0;
	char *name="Redio/*"; 
     if(glob(name,0,NULL,&pglob)!=0)
	{
		fprintf(stdout,"The parth is not exist\n");
		exit(1);
	}
    list=malloc(sizeof(ch_list));
	if(list==NULL)
	{
		printf("malloc is wrong\n");
		exit(1);
	}
	list->size=pglob.gl_pathc;
	list->list=malloc(sizeof(ch_desc*)*list->size);
	if(list==NULL)
	{
		printf("malloc is wrong\n");
		exit(1);
	}

	for(i=0;i<pglob.gl_pathc;i++)
	{
		if(lstat(pglob.gl_pathv[i],&buf)<0)
		{
			perror("lstat()");
			exit(1);
		}
	if((buf.st_mode&S_IFDIR)==S_IFDIR)
	{   
          
		sp=next_name(pglob.gl_pathv[i]);
           if(sp==NULL)
		   {
			  exit(1);
		   }
		   chnum=atoi(sp)-1;
		strcat(pglob.gl_pathv[i],"/desc.txt");
		if(lstat(pglob.gl_pathv[i],&buf)<0)
		{
			
			if(errno==ENOENT)
				continue;
			exit(1);
		}
		fp=open(pglob.gl_pathv[i],O_RDONLY);
		if(fp<0)
		{
			if(errno==ENOENT)
				continue;
			exit(1);
			
		}
		list->list[chnum]=malloc(sizeof(ch_desc)+buf.st_size-1);
		list->list[chnum]->size=buf.st_size;
		size=buf.st_size;
		pos=0;
		
		while((len=read(fp,list->list[chnum]->data+pos,size))>0)
		{
			     pos+=len;
				 size-=len;
		}
		
                close(fp);

	    strcpy(list->list[chnum]->name,pglob.gl_pathv[i]);
				
		continue;
	}
	}
	
	return list;
}
void destory_list(ch_list *p)
{
	int i;
	for(i=0;i<p->size;i++)
	{
		free(p->list[i]);
	}
	free(p->list);
	free(p);
	return ;
}
